package com.simplerobot.util;

import org.apache.log4j.Logger;

import java.io.*;


public class FileUtil {
    public static Logger log4j = Logger.getLogger(FileUtil.class);

    public static String readAllText(String fileName) {
        if (!exists(fileName, false)) {
            return "";
        }
        StringBuilder str = new StringBuilder();
        String line = null;
        try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
            while ((line = reader.readLine()) != null) {
                str.append(line);
            }
        } catch (Exception ex) {
            log4j.error(String.format("加截文件失败：%s", fileName), ex);
            return "";
        }
        return str.toString();
    }


    public static boolean writeAllText(String fileName, String content) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
            writer.write(content);
            return true;
        } catch (Exception ex) {
            log4j.error(String.format("写入文本到文件失败：%s", fileName), ex);
            return false;
        }
    }


    public static Boolean exists(String fileName, Boolean isDirectory) {
        if (isDirectory == null) {
            isDirectory = false;
        }
        if (isDirectory) {
            File file = new File(fileName);
            return file.exists() && file.isDirectory();
        }
        return new File(fileName).exists();
    }

    public static void notExistsDirectoryCreate(String fileName) {
        if (!exists(fileName, true)) {
            new File(fileName).mkdirs();
        }
    }

    public static String getExtension(String fileName) {
        if (fileName == null || fileName.length() < 1) {
            return "";
        }
        return fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
    }
}